Object.defineProperty(window.$twApp, 'ekey', {
  value: window.$twApp.encodeRequest ? '0nzNUZQLBWlBjPcu' : ''
})

if (!window.$twApp.eco) {
  window.$twApp.eco = {}
}

if (window.$twApp.loginPage) {
  window.$twApp.eco.loginPage = window.$twApp.loginPage
}

if (window.$twApp.ecoWebServer) {
  window.$twApp.eco.ecoWebServer = window.$twApp.ecoWebServer
}

window.$twApp.accreditCodeTime = 240000
window.$twApp.user = {}
window.Vue.prototype.$twApp = window.Vue.observable(window.$twApp)
window.Vue.prototype.$siteConfig = window.$siteConfig

function initUI () {
  // <link rel="icon" type="image/png" href="/unified-portal/images${this.$api.site.get.data.logoPath}" />
  if (window.$siteConfig && window.$siteConfig.logoPath) {
    var link = document.createElement('link')
    link.href = window.$twApp.fileBaseUrl + window.$siteConfig.logoPath
    link.rel = 'icon'
    link.type = 'image/png'
    document.querySelector('head').appendChild(link)
  }

  if (/* @cc_on!@ */false || !!document.documentMode) {
    window.onload = function() {
      var script = document.createElement('script')
      script.src = './lib/js/ie-cover.js'
      document.head.appendChild(script)
    }
  }
}

initUI()

if (typeof Object.assign !== 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, 'assign', {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict'
      if (target === null || target === undefined) {
        throw new TypeError('Cannot convert undefined or null to object')
      }

      var to = Object(target)

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index]

        if (nextSource !== null && nextSource !== undefined) {
          for (var nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey]
            }
          }
        }
      }
      return to
    },
    writable: true,
    configurable: true
  })
}

var cookie = {
  set: function (name, value, expires) {
    if (!expires) {
      expires = 12
    }

    if (value) {
      if (expires) {
        expires = new Date(new Date() * 1 + 60 * 60 * 1000 * expires).toUTCString()
      }

      // window.document.cookie = `${name}=${encodeURIComponent(value)};path=/;${expires ? 'expires=' + expires : ''}`
      window.document.cookie = name + '=' + encodeURIComponent(value) + ';path=/;' + (expires ? 'expires=' + expires : '')
    }
  },

  get: function (name) {
    // let value = window.document.cookie.match(`(^|;) ?${name}=([^;]*)(;|$)`)
    var value = window.document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)')
    return value && decodeURIComponent(value[2])
  }
}

cookie['delete'] = function (name) {
  this.set(name, name, -1)
}

if (!window.$ui) {
  window.$ui = {}
}

window.$ui.toEncryption = function (value) {
  var CryptoJS = window.CryptoJS
  var key = CryptoJS.enc.Utf8.parse(window.$twApp.ekey)
  return CryptoJS.AES.encrypt(value, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString()
}

window.$ui.toDecrypt = function (value) {
  var CryptoJS = window.CryptoJS
  var key = CryptoJS.enc.Utf8.parse(window.$twApp.ekey)
  return CryptoJS.AES.decrypt(value, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString(CryptoJS.enc.Utf8)
}

window.$ui.genImagePath = function (imgPath) {
  if (/^(http:|https:)/.test(imgPath)) {
    return imgPath
  } else {
    return window.$twApp.fileBaseUrl + imgPath
  }
}

window.axios.interceptors.request.use(function (config) {
  if (config.url.indexOf('/tw-cloud-datatheme-server') !== -1) {
    if (config.data.conditions) {
      var conditions = []

      config.data.conditions.forEach(function(item) {
        if (item.fieldValues && item.fieldValues.length > 0 && item.fieldValues[0]) {
          conditions.push(item)
        }
      })

      config.data.conditions = conditions
    }

    if (window.$twApp.ekey) {
      config.data = window.$ui.toEncryption(JSON.stringify(config.data))
    }
  }

  return config
}, function (error) {
  return Promise.reject(error)
})

window.axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
  if (error.code === 'ECONNABORTED' || (error.response && error.response.status === 408)) {
    window.$ui.msg({
      type: 'error',
      message: '请求超时，请检查网络或刷新页面重试',
      customClass: 'xtop'
    })
  }

  if (error.response && error.response.data) {
    var errorCode = error.response.data.resultCode

    if (errorCode && [4210, 4211].includes(errorCode)) {
      // 在iframe中不弹出对话框，直接退出
      if (window === window.top) {
        window.$ui.msgBox({
          title: '请登录',
          type: 'warning',
          message: '登录状态已过期，或在其他设备上登录！',
          confirmButtonText: '确定',
          showCancelButton: false,
          showClose: false
        }).then(function () {
          window.$twApp.logoff()
        })
      } else {
        window.$ui.msg('登录状态已过期，请重新登录~')
        setTimeout(() => {
          window.$twApp.logoff()
        }, 3000)
      }
    }

    if (errorCode && [4000, 4010].includes(errorCode)) {
      window.$ui.msg({
        type: 'error',
        customClass: 'xtop',
        message: '请求错误，请稍后重试或重新登录~'
      })
    }
  }

  return Promise.reject(error)
})

window.$ui.cookie = cookie

Object.defineProperty(window.$ui, 'urlQuery', {
  get: function () {
    var result = {}
    var href = window.location.href.replace(/\/?#\/$/, '')
    var queryArr = href.substr(href.indexOf('?') + 1).split('&')

    queryArr.forEach(function (q) {
      var item = q.split('=')
      result[item[0].trim()] = decodeURIComponent(item[1] ? item[1].trim() : '')
    })

    return result
  }
})

window.$ui.getAccreditCode = function (path, params) {
  var token = window.$twApp.user.token

  return window.axios.post(window.$twApp.gateway + '/openapi-uc/accreditcode/getAccreditCode', {
    accessToken: token,
    userId: window.$twApp.user.userId
  }).then(function (data) {
    var serverResult = data.data.serverResult
    var responseEntity = data.data.responseEntity

    if (serverResult.resultCode === '200' && responseEntity.accreditCode) {
      window.Vue.set(window.$twApp.user, 'accreditCode', responseEntity.accreditCode)
      window.Vue.set(window.$twApp.user, 'accreditUrl', 'accredit_code=' + responseEntity.accreditCode + '&access_token=' + token + '&token=' + token)

      if (window.$lib.vm) {
        window.$lib.vm.$forceUpdate()
      }

      if (path) {
        window.open(path + '?accredit_code=' + responseEntity.accreditCode + '&access_token=' + token + '&token=' + token + (params ? window.$ui.qs.stringify(params) : ''), '_blank')
      } else {
        return responseEntity.accreditCode
      }
    } else {
      return new Error('failed to get the acredit code.')
    }
  })
}

window.$ui.openApp = function (path, params) {
  window.$ui.getAccreditCode(path, params)
}

window.$ui.computeBodyHeight = function () {
  document.body.style.minHeight = '0'
  var bodyHeight = document.body.scrollHeight
  var footerEl = document.querySelector('.tw-libfooter')

  if (footerEl) {
    bodyHeight += footerEl.clientHeight
  }

  if (bodyHeight < window.innerHeight) {
    bodyHeight = window.innerHeight
  }

  document.body.style.minHeight = bodyHeight + 'px'
}

window.$ui.html2Text = function (html, len) {
  var div = document.createElement('div')
  div.innerHTML = html
  var text = div.innerText
  return len ? text.substring(0, len) : text
}

window.$ui.el = {
  innerWidth: function (el) {
    if (el) {
      return el.offsetWidth - parseInt(window.getComputedStyle(el).paddingLeft) - parseInt(window.getComputedStyle(el).paddingRight) - parseInt(window.getComputedStyle(el).borderLeft) - parseInt(window.getComputedStyle(el).borderRight)
    } else {
      return 0
    }
  }
}

window.$ui.getWeek = function(timestamp) {
  var now = new Date(timestamp)
  var onejan = new Date(now.getFullYear(), 0, 1)
  return Math.ceil((((now - onejan) / 86400000) + onejan.getDay() + 1) / 7)
}

window.$ui.setTimeParams = function (timestamp) {
  var now = new Date(timestamp)
  window.$twApp.now = timestamp
  window.$twApp.year = now.getFullYear() + 0
  window.$twApp.month = now.getMonth() + 1
  window.$twApp.date = window.$ui.dateFormat(now, 'yyyy-mm-dd')
  window.$twApp.dateNo = now.getDate() + 0
  window.$twApp.week = window.$ui.getWeek(now) + 0
  window.$twApp.day = now.getDay() + 0
  window.$twApp.time = window.$ui.dateFormat(now, 'hh:mm:ss')
  window.$twApp.hour = now.getHours() + 0
  window.$twApp.minute = now.getMinutes() + 0
  window.$twApp.second = now.getSeconds() + 0

  window.$twApp.yearId = window.$twApp.year

  if (window.$twApp.month < 9) {
    window.$twApp.yearId -= 1
  }

  window.$twApp.lastWeek = [window.$ui.dateFormat(new Date(timestamp - 604800000), 'yyyy-mm-dd'), window.$twApp.date]
  window.$twApp.lastMonth = [window.$ui.dateFormat(new Date(timestamp - 2592000000), 'yyyy-mm-dd'), window.$twApp.date]
  window.$twApp.lastYear = [window.$ui.dateFormat(new Date(timestamp - 31536000000), 'yyyy-mm-dd'), window.$twApp.date]
}

window.$ui.getServeTime = function () {
  window.axios.get(window.$twApp.gateway + '/openapi-uc/oauth/time/get').then(function (resp) {
    if (resp.data && resp.data.responseEntity) {
      window.$ui.setTimeParams(resp.data.responseEntity)
    } else {
      window.$ui.setTimeParams(Date.now())
    }
  }).catch(function (e) {
    window.$ui.setTimeParams(Date.now())
  })
}

window.$ui.extToFileType = function (file, fromExt) {
  if (fromExt) {
    file = '*.' + file
  }

  const ext = file.substring(file.lastIndexOf('.') + 1).toLowerCase()

  const extMap = Object.assign({
    text: ['txt'],
    pdf: ['pdf'],
    ppt: ['ppt', 'pptx'],
    word: ['doc', 'docx'],
    flash: ['swf', 'flv'],
    excel: ['xls', 'xlsx'],
    image: ['jpg', 'jpeg', 'png', 'gif'],
    video: ['mp4', 'ogg', 'wmv', 'aiv'],
    audio: ['mp3', 'aac', 'm4a', 'wav'],
    zip: ['zip', 'rar', '7z']
  })

  for (const key in extMap) {
    if (extMap.hasOwnProperty(key)) {
      const element = extMap[key]

      if (element.includes(ext)) {
        return key
      }
    }
  }

  return 'other'
}

window.$ui.fileToIconCss = function(file, size, fromExt) {
  if (!size) size = '24'
  const type = window.$ui.extToFileType(file, fromExt)
  return 'tw-ico x' + size + ' xr' + type
}

window.$ui.getServeTime()
window.$ui.setTimeParams(Date.now())

var vm = new window.Vue()
var msgs = null

if (vm.$message) {
  msgs = {
    msg: vm.$message,
    msgBox: vm.$msgbox,
    confirm: vm.$msgbox.confirm,
    alert: vm.$msgbox.alert,
    loading: vm.$loading
  }
} else {
  msgs = {
    msg: vm.$toast,
    msgBox: vm.$dialog.alert,
    confirm: vm.$dialog.confirm,
    alert: vm.$dialog.alert,
    loading: vm.$toast.loading
  }
}

Object.assign(window.$ui, msgs)
window.Vue.prototype.$ui = window.Vue.observable(window.$ui)
